﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;

namespace Admin.NET.Application
{
    /// <summary>
    /// 测试老师表服务
    /// </summary>
    [ApiDescriptionSettings("测试老师表", Name = "TestTeacher", Order = 100)]
    [Route("api/[Controller]")]
    public class TestTeacherService : ITestTeacherService, IDynamicApiController, ITransient
    {
        private readonly IRepository<TestTeacher,MasterDbContextLocator> _testTeacherRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();

        public TestTeacherService(
            IRepository<TestTeacher,MasterDbContextLocator> testTeacherRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
        )
        {
            _testTeacherRep = testTeacherRep;
         _sysDictTypeRep = sysDictTypeRep;
         _sysDictDataRep = sysDictDataRep;
         _sysExcelTemplateService = sysExcelTemplateService;
        }

        /// <summary>
        /// 分页查询测试老师表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<TestTeacherOutput>> Page([FromQuery] TestTeacherSearch input)
        {
            var testTeachers = await _testTeacherRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.Name), u => u.Name == input.Name)
                                     .OrderBy(PageInputOrder.OrderBuilder<TestTeacherSearch>(input))
                                     .ProjectToType<TestTeacherOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return testTeachers;
        }

        /// <summary>
        /// 不分页查询测试老师表列表
        /// </summary>
        /// <param name="input">测试老师表查询参数</param>
        /// <returns>(测试老师表)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<TestTeacherOutput>> ListNonPageAsync([FromQuery] TestTeacherSearchNonPage input)
        {
            var pName = input.Name?.Trim() ?? "";
            var testTeachers = await _testTeacherRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pName), u => u.Name == pName)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<TestTeacherOutput>()
            .ToListAsync();
            return testTeachers;
        }


        /// <summary>
        /// 增加测试老师表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddTestTeacherInput input)
        {
            var testTeacher = input.Adapt<TestTeacher>();
            await _testTeacherRep.InsertAsync(testTeacher);
        }

        /// <summary>
        /// 删除测试老师表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteTestTeacherInput input)
        {
            var testTeacher = await _testTeacherRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _testTeacherRep.DeleteAsync(testTeacher);
        }

        /// <summary>
        /// 更新测试老师表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateTestTeacherInput input)
        {
            var isExist = await _testTeacherRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var testTeacher = input.Adapt<TestTeacher>();
            await _testTeacherRep.UpdateAsync(testTeacher,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取测试老师表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<TestTeacherOutput> Get([FromQuery] QueryeTestTeacherInput input)
        {
            return (await _testTeacherRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<TestTeacherOutput>();
        }

        /// <summary>
        /// 获取测试老师表列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<TestTeacherOutput>> List([FromQuery] TestTeacherInput input)
        {
            return await _testTeacherRep.DetachedEntities.ProjectToType<TestTeacherOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入测试老师表功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("TestTeacher", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<TestTeacherOutput> testTeacherList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, TestTeacherOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = testTeacherList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<TestTeacher>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<TestTeacher, TestTeacherOutput>(selectKeys);
            List<TestTeacher> updates = new();
            List<TestTeacher> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var testTeacherExistSubList = _testTeacherRep.Where(filter).Select(selector).ToList();
                    testTeacherExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var testTeacher in testTeacherList) 
                {
                    if (testTeacher.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(testTeacher.Adapt<TestTeacher>());
                    }
                    else 
                    {
                        adds.Add(testTeacher.Adapt<TestTeacher>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _testTeacherRep.Update(x));
                

                var maxId = _testTeacherRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<TestTeacher>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载测试老师表的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("TestTeacher", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据测试老师表查询参数导出Excel
        /// </summary>
        /// <param name="input">测试老师表查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] TestTeacherSearchNonPage input)
        {
            var testTeacherList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(testTeacherList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("TestTeacher", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
